import urllib.parse
from django.contrib.auth.hashers import make_password
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.generic.base import View
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from cloud_hr import settings
from .forms import *
from django.urls import reverse
from django.contrib.auth import authenticate
import random
import logging
import json
from django.views.decorators.csrf import csrf_exempt
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models

logger = logging.getLogger(__name__)


@csrf_exempt
def send_sms_code(request):
    try:
        cred = credential.Credential("AKIDa1GI9p3OYWGoAJG0Zw75qRq46wZ1HLDr", "WqwoUxDH8oJZbYMyMbeU7XlneIjz2ua5")
        # 实例化一个http选项，可选的，没有特殊需求可以跳过
        httpProfile = HttpProfile()
        httpProfile.endpoint = "sms.tencentcloudapi.com"

        # 实例化一个client选项，可选的，没有特殊需求可以跳过
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        # 实例化要请求产品的client对象,clientProfile是可选的
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,每个接口都会对应一个request对象
        req = models.SendSmsRequest()
        if request.method == "POST":
            mobile_phone = json.loads(request.body).get("mobile_phone")
            code = generate_code()
            request.session["code"] = code
            params = {
                "PhoneNumberSet": [mobile_phone],
                "SmsSdkAppId": "1400855213",
                "SignName": "大四实训公众号",
                "TemplateId": "1932231",
                "TemplateParamSet": [code]
            }
            req.from_json_string(json.dumps(params))
            resp = client.SendSms(req)
            # 如果发送成功，可以返回一些成功信息
            return JsonResponse({"message": "验证码发送成功"})
    except TencentCloudSDKException as e:
        # 处理异常，可以记录日志或返回错误信息
        return JsonResponse({"error": str(e)})


def generate_code():
    code = str(random.randint(10000, 99999))
    return code


def menu(request):
    user = request.session["user_name"]
    identity = User.objects.get(user_name=user).identity
    return render(request, "menu.html", {"user_name": user, "identity": identity})


def register(request):
    if request.method == "GET":
        return render(request, "signup.html")
    if request.method == "POST":
        forms = RegisterForm(request.POST)
        code = request.POST.get("sms_code")
        if forms.is_valid() and code == request.session["code"]:
            request.session['mobile_phone'] = forms.cleaned_data['mobile_phone']
            register = forms.save(commit=False)
            register.is_active = 1
            register.password = make_password(forms.cleaned_data['password'])
            register.save()
            request.session['user_name'] = forms.cleaned_data['user_name']
            return redirect(reverse("signin"))
        else:
            return render(request, "signup.html", {"forms": forms})


def choose_identify(request):
    user_name = request.session["user_name"]
    # 获取user对象
    user = User.objects.get(user_name=user_name)
    if user:
        identity = request.POST.get("identity")
        user.identity = identity
        user.save()
        return redirect(reverse("menu"))


class LoginView(View):
    def get(self, request):
        return render(request, "signin.html")

    def post(self, requset):
        loginForm = LoginForm(requset.POST)
        if not loginForm.is_valid():
            return render(requset, "signin.html", {"forms": loginForm})
        user_name = loginForm.cleaned_data["user_name"]
        password = loginForm.cleaned_data["password"]
        if user_name.find("@") > 0:
            user_obj = User.objects.filter(email=user_name)
            if len(user_obj) > 0:
                user_name = user_obj[0].user_name
        user = authenticate(user_name=user_name, password=password)
        if user is not None:
            identify = user.identity
        else:
            return render(requset, "signin.html")
        if user and identify is not None:
            requset.session["user_name"] = user_name
            return redirect(reverse("menu"))
        elif user and identify is None:
            requset.session["user_name"] = user_name
            return render(requset, "choose_identity.html")
        else:
            return render(requset, "signin.html", {"error": "用户名或密码错误"})


def detail_list(request):
    user_name = request.session.get("user_name")
    # 获取user对象
    user = User.objects.get(user_name=user_name)
    identity = user.identity
    if identity == 1:
        user_list = User.objects.all().order_by("-create_time")
        paginator = Paginator(user_list, settings.PAGE_SIZE)
        page_number = request.GET.get('page')
        try:
            page_obj = paginator.get_page(page_number)
        except PageNotAnInteger:
            page_obj = paginator.get_page(1)
        except EmptyPage:
            page_obj = paginator.get_page(paginator.num_pages)
        return render(request, "index.html", {"user_list": page_obj, "page_obj": page_obj, "identity": identity})
    else:
        user_list = User.objects.filter(user_name=user.user_name)
        paginator = Paginator(user_list, settings.PAGE_SIZE)
        page_number = request.GET.get('page')
        try:
            page_obj = paginator.get_page(page_number)
        except PageNotAnInteger:
            page_obj = paginator.get_page(1)
        except EmptyPage:
            page_obj = paginator.get_page(paginator.num_pages)
        return render(request, "index.html", {"user_list": page_obj, "page_obj": page_obj})


def update_detail(request):
    user_id = request.POST.get("user_id")
    user = User.objects.get(id=user_id)

    # 获取新用户名和新密码
    new_user_name = request.POST.get("new_user_name")
    new_password = request.POST.get("new_password")

    # 创建一个字典来存储要更新的字段和它们的新值
    fields_to_update = {}

    if new_user_name is not None and new_user_name != "":
        fields_to_update['user_name'] = new_user_name
    if new_password is not None and new_password != "":
        fields_to_update['password'] = make_password(new_password)

    # 更新用户对象的字段
    if user:
        for field, value in fields_to_update.items():
            setattr(user, field, value)
        user.save()

    return redirect(reverse("menu"))


@csrf_exempt
def forbidden_or_activate(request):
    if request.method == "POST":
        data = request.body
        data = data.decode("utf-8")
        query_params = urllib.parse.parse_qs(data)
        user_id = query_params.get('user_id', [''])[0]
        is_active = query_params.get('action', [''])[0]
        user = User.objects.get(id=user_id)
        user.is_active = is_active
        print(user_id, "===", is_active)
        user.save()
    return redirect(reverse("detail_list"))


def quit(request):
    del request.session["user_name"]
    return redirect(reverse("signin"))
